﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

using System.Text.Json;
using System.Text.Json.Nodes;
using InTheHand.Net;

namespace MyTRCP.Common.Services
{
    public class ClientConfigService : IConfigService
    {
        private enum ConfigFuncEnum : ulong { NONE = 0, DEV_MACS = 0X1, LAST_CONN_DEV_INDEX = 0X2, ALL = 0XFFFFFFFFFFFFFFFF }
        private readonly ILogger<ClientConfigService> _logger;
        private readonly IConfiguration _configuration;
        private readonly List<BluetoothAddress> _savedDevMacs;
        public AppTypeEnum AppType
        {
            get { return AppTypeEnum.Client; }
        }
        public ClientModeEnum ClientMode { get; private set; }
        public List<BluetoothAddress> SavedDevMacs { get { return _savedDevMacs; } }
        public int LastConnDevIndex { get; set; }
        public ClientConfigService(ILogger<ClientConfigService> logger, IConfiguration conf)
        {
            _logger = logger;
            _configuration = conf;
            _savedDevMacs = new List<BluetoothAddress>();
            IConfigurationSection cm = conf.GetSection("ClientMode");
            if (cm.Value != null && cm.Value.Equals("Remote", StringComparison.CurrentCultureIgnoreCase))
            {
                ClientMode = ClientModeEnum.Remote;
                _logger.LogDebug("客户端以远程模式运行");
            }
            else
            {
                ClientMode = ClientModeEnum.Local;
                _logger.LogDebug("客户端以本地模式运行");
            }
            cm = conf.GetSection("SavedDevMacs");
            foreach (var mac in cm.GetChildren())
            {
                if (mac.Value != null)
                {
                    _savedDevMacs.Add(BluetoothAddress.Parse(mac.Value));
                }
            }
            cm = conf.GetSection("LastConnDevIndex");
            LastConnDevIndex = int.Parse(cm.Value);
        }
        private void SaveConfig(ConfigFuncEnum saveFuncFlag)
        {
            string jsonFilePath = "appsettings.json";
            if (File.Exists(jsonFilePath))
            {
                string json = File.ReadAllText(jsonFilePath);
                var options = new JsonSerializerOptions { WriteIndented = true };
                var config = JsonSerializer.Deserialize<JsonObject>(json);
                if ((saveFuncFlag & ConfigFuncEnum.DEV_MACS) > 0)
                {
                    JsonArray ja = new JsonArray();
                    foreach (BluetoothAddress ba in _savedDevMacs)
                    {
                        ja.Add(ba.ToString("C"));
                    }
                    config["SavedDevMacs"] = ja;
                }
                if ((saveFuncFlag & ConfigFuncEnum.LAST_CONN_DEV_INDEX) > 0)
                {
                    config["LastConnDevIndex"] = LastConnDevIndex;
                }
                string updateJson = JsonSerializer.Serialize(config, options);
                File.WriteAllText(jsonFilePath, updateJson);
            }
            else
            {
                _logger.LogError("未找到配置文件，无法保存设备mac");
            }
        }
        public void SaveDevMacs()
        {
            SaveConfig(ConfigFuncEnum.DEV_MACS);
        }
        public void SaveLastConnDevIndex()
        {
            SaveConfig(ConfigFuncEnum.LAST_CONN_DEV_INDEX);
        }
        public void SaveAll()
        {
            SaveConfig(ConfigFuncEnum.ALL);
        }
    }
}
